<?php

namespace App\Http\Controllers;

use App\Http\Filters\MembersFilter;
use App\Http\Requests\Members\FilterRequest;
use App\Http\Requests\Members\MembersStoreRequest;
use App\Http\Requests\Members\MembersUpdateRequest;
use App\Http\StaticData;
use App\Models\Behavior;
use App\Models\Centers;
use App\Models\Diseases;
use App\Models\Members;
use App\Models\Rehabilitation;
use App\Models\Sickness;
use App\Models\Skill;
use App\Models\User;
use App\Models\Walking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Rap2hpoutre\FastExcel\FastExcel;

class MembersController extends Controller
{
    use StaticData;

    public function show(FilterRequest $request)
    {

        $currentCenters = [];

        foreach (User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }


        if (!in_array(3, $currentCenters)) {
            $centers = Centers::where('user_id', Auth::id())->get();
        } else {
            $centers = Centers::all();
        }


        $data = $request->validated();


        if (isset($data['filters'])) {
            if (!isset($data['filters']['centers_id'])) {
                $data['filters']['centers_id'] = $centers->pluck('id')->toArray();
            }

            $filter = app()->make(MembersFilter::class, ['queryParams' => array_filter($data['filters'])]);

            $members = Members::filter($filter)->paginate(30);
        } else {
            if (!isset($data['filters']['centers_id'])) {
                $filterCenter['centers_id'] = $centers->pluck('id')->toArray();
            }
            $filter = app()->make(MembersFilter::class, ['queryParams' => array_filter($filterCenter)]);
            $members = Members::filter($filter)->paginate(30);
        }


        $totalItems = $members->total();
        $currentPage = $members->currentPage();
        $perPage = 30;


        $sickness = Sickness::all();



        return view('members.show', compact('sickness', 'members', 'centers', 'totalItems', 'currentPage', 'perPage'));
    }

    public function excel(FilterRequest $request)
    {

        $currentCenters = [];

        foreach (User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }

        $data = $request->validated();


        if (!in_array(3, $currentCenters)) {
            $members = Members::query();
            $members->whereIn('centers_id', $currentCenters);
            $members = $members->get();
        } else {
            $members = Members::all();
        }

        if (!in_array(3, $currentCenters)) {
            $centers = Centers::where('user_id', Auth::id())->get();
        } else {
            $centers = Centers::all();
        }


        if (isset($data['filters'])) {


            if (!isset($data['filters']['centers_id'])) {
                $data['filters']['centers_id'] = $centers->pluck('id')->toArray();
            }


            $filter = app()->make(MembersFilter::class, ['queryParams' => array_filter($data['filters'])]);


            $members = Members::filter($filter)->with(['skills' => function($query) {
                $query->select('name');
            }])->get();
            unset($data['filters']['diagnosis']);

        } else {
            if (!in_array(3, $currentCenters)) {

                if (!isset($data['filters']['centers_id'])) {
                    $filterCenter['centers_id'] = $centers->pluck('id')->toArray();
                }

                $filter = app()->make(MembersFilter::class, ['queryParams' => array_filter($filterCenter)]);
                $members = Members::filter($filter)->with(['skills' => function($query) {
                    $query->select('name');
                }])->get();
            } else {
                $members = Members::with(['skills' => function($query) {
                    $query->select('name');
                }])->get();

            }


        }




        $data = $members->map(function ($member, $key) {

            return [
                'Номер' => $key + 1,
                'ФИО' => $member->fullname,
                'Дата рождения' => $member->birthday,
                'Диагноз (основной)' => $member->diagnosis,
                'ФИО представителя' => $member->fullname_agent,
                'Почта представителя' => $member->email,
                'Телефон представителя' => $member->agent_phone,
                'Центр' => $member->center->name,
                'Характеристика навыков ходьбы' => $member->walkings->implode('name', ', '),
                'Особенности поведения, свойственные ребенку' => $member->behaviors->implode('name', ', '),
                'Общее физическое состояние' => $member->physical_condition,
                'Сопутствующие заболевания' => $member->diseases->implode('name', ', '),
                'Какими навыками обладает ребенок' => $member->skills->implode('name', ', '),
                'Посещение других реабилитационных программ' => $member->rehabilitations->implode('name', ', '),
            ];
        });

        $fileName = uniqid() . '.xlsx';
        (new FastExcel($data))->export($fileName);

        return DIRECTORY_SEPARATOR . $fileName;
    }

    public function edit(Members $member)
    {
        $currentCenters = [];

        foreach (User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }

        if (!in_array(3, $currentCenters)) {
            $centers = Centers::query();
            $centers->whereIn('id', $currentCenters);
            $centers = $centers->get();
        } else {
            $centers = Centers::all();
        }


        $memberRehabilitations = $member->rehabilitations;
        $memberRehabilitationsIds = $memberRehabilitations->pluck('id')->toArray();

        $memberSkills = $member->skills;
        $memberSkillsIds = $memberSkills->pluck('id')->toArray();

        $memberDiseases = $member->diseases;
        $memberDiseasesIds = $memberDiseases->pluck('id')->toArray();

        $memberBehaviors = $member->behaviors;
        $memberBehaviorsIds = $memberBehaviors->pluck('id')->toArray();

        $memberWalkings = $member->walkings;
        $memberWalkingsIds = $memberWalkings->pluck('id')->toArray();

        $skills = Skill::all();
        $rehabilitations = Rehabilitation::all();
        $sickness = Sickness::all();
        $diseases = Diseases::all();
        $behaviors = Behavior::all();
        $walkings = Walking::all();

        return view('members.edit', compact('member', 'memberWalkingsIds','walkings','behaviors','memberBehaviorsIds','diseases','memberDiseasesIds','sickness','memberSkillsIds','memberRehabilitationsIds','rehabilitations','skills', 'centers'));

    }

    public function update(MembersUpdateRequest $request, Members $member)
    {


        $data = $request->validated();


        $member->update([
            'fullname' => $data['fullname'],
            'birthday' => $data['birthday'],
            'diagnosis' => $data['diagnosis'],
            'fullname_agent' => $data['fullname_agent'],
            'agent_phone' => $data['agent_phone'],
            'centers_id' => $data['centers_id'],
            'email' => $data['email'],
            'physical_condition' => $data['physical_condition'],
        ]);


        if ($request->has('skills')) {
            $member->skills()->sync($data['skills']);
        }

        if ($request->has('rehabilitation')) {
            $member->rehabilitations()->sync($data['rehabilitation']);
        }

        if ($request->has('diseases')) {
            $member->diseases()->sync($data['diseases']);
        }

        if ($request->has('behavior')) {
            $member->behaviors()->sync($data['behavior']);
        }

        if ($request->has('walking')) {
            $member->walkings()->sync($data['walking']);
        }

        $member->save();

        return redirect(route('members'));
    }

    public function add(Members $member)
    {
        $currentCenters = [];

        foreach (User::find(Auth::id())->centers as $center) {
            $currentCenters[] = $center->id;
        }

        if (!in_array(3, $currentCenters)) {
            $centers = Centers::query();
            $centers->whereIn('id', $currentCenters);
            $centers = $centers->get();
        } else {
            $centers = Centers::all();
        }
        $skills = Skill::all();
        $rehabilitations = Rehabilitation::all();
        $diseases = Diseases::all();
        $behaviors = Behavior::all();
        $walkings = Walking::all();
        $sickness = Sickness::all();

        return view('members.add', compact(
            'centers',
            'rehabilitations',
            'skills',
            'behaviors',
            'walkings',
            'diseases',
            'sickness',
        ));
    }

    public function store(MembersStoreRequest $request)
    {
        $data = $request->validated();



        $member = Members::create([
            'fullname' => $data['fullname'],
            'birthday' => $data['birthday'],
            'diagnosis' => $data['diagnosis'],
            'fullname_agent' => $data['fullname_agent'],
            'agent_phone' => $data['agent_phone'],
            'centers_id' => $data['centers_id'],
            'email' => $data['email'],
            'physical_condition' => $data['physical_condition'],
        ]);


        if ($request->has('skills')) {
            $member->skills()->attach($data['skills']);
        }

        if ($request->has('rehabilitation')) {
            $member->rehabilitations()->attach($data['rehabilitation']);
        }

        if ($request->has('diseases')) {
            $member->diseases()->attach($data['diseases']);
        }

        if ($request->has('behavior')) {
            $member->behaviors()->attach($data['behavior']);
        }

        if ($request->has('walking')) {
            $member->walkings()->attach($data['walking']);
        }

        $member->save();


        return redirect(route('members'));
    }

    public function delete(Request $request, Members $member)
    {

        $forDelete = Members::find($member->id);
        if (!$forDelete->delete()) {
            throw new \Exception('Невозможно удалить запись');
        } else {
            return redirect(route('members'));
        }

    }


}
